package com.junshang.JUC_day1;


import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by sahngjun on 2017/3/23.
 */
public class TestReadWriteLock {
    public static ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();

    public static void main(String[] args) {
        Map map = new ConcurrentHashMap();
        List<Integer> list = new LinkedList<>();
        for (int i = 1; i <= 1000000; i++) {
            new Thread(new Runnable() {
                public void run() {
                    readWriteLockDemo.get();
                }
            }, "read").start();
        }
        new Thread(new Runnable() {
            public void run() {
                readWriteLockDemo.set((int) (Math.random() * 100));
            }
        }, "write").start();
    }

}

class ReadWriteLockDemo {
    public ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public int num = 0;

    public void get() {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "--" + num);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void set(int num) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + num);
            this.num = num;
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}
